package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.TradeQueryCri;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.TimeUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.HorizontalItemView;
import com.eeepay.v2_library.view.LabelEditText;
import com.eeepay.v2_library.view.TitleBar;

import static com.eeepay.eeepay_v2.util.Constant.RequestCode.agent_all;

/**
 * Created by zw on 2016/2/29 0029.
 * 交易超级查询
 */
public class TradeQueryActivity extends ABBaseActivity implements View.OnClickListener {

    private TitleBar titleBar;
    private TextView[] time_select = new TextView[3];//时间选择框
    private TextView start_time, end_time;//开始时间和结束时间
    private EditText trade_minMoney, trade_maxMoney; //交易金额
    private EditText et_agent_input; //代理商名称
    private TextView tv_select_agent; //代理商名称选择
    private HorizontalItemView  trade_state_all, device_all, card_all;//agent_all,
    private LabelEditText cardNum, phoneLet, tradeName;
    private EditText into_startDate, into_endDate;//进件时间
    private Button btn_confirm;

    private String tradeStatusId = "SUCCESS";
    private String hpId = "";
    private String agentNode = "";//代理商节点
    //交易超级查询条件
    private TradeQueryCri tradeQueryCri;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_trade_query;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.title_bar);
        titleBar.setShowRight(View.VISIBLE);
        titleBar.setRightTextView("重置");
        titleBar.setRightTextColor(R.color.unify_grounding_white);

        time_select[0] = getViewById(R.id.tv_select_1);
        time_select[0].setTag(1);
        time_select[1] = getViewById(R.id.tv_select_2);
        time_select[1].setTag(3);
        time_select[2] = getViewById(R.id.tv_select_3);
        time_select[2].setTag(6);

        //开始时间
        start_time = getViewById(R.id.start_time);
        //结束时间
        end_time = getViewById(R.id.end_time);
        //交易金额
        LinearLayout lLayout_trade_money = getViewById(R.id.trade_money);
        trade_minMoney = (EditText) lLayout_trade_money.findViewById(R.id.input_1);
        trade_minMoney.setInputType(com.google.protobuf.Type.FIELDS_FIELD_NUMBER);//输入内容限制
        trade_maxMoney = (EditText) lLayout_trade_money.findViewById(R.id.input_2);
        trade_maxMoney.setInputType(com.google.protobuf.Type.FIELDS_FIELD_NUMBER);
        //进件时间
        LinearLayout lLayout_into_time = getViewById(R.id.into_date);
        into_startDate = (EditText) lLayout_into_time.findViewById(R.id.input_1);
        into_startDate.setFocusableInTouchMode(false);
        into_endDate = (EditText) lLayout_into_time.findViewById(R.id.input_2);
        into_endDate.setFocusableInTouchMode(false);
        //add by zhuangzeqin 2017年4月26日10:25:59 增加文本内容观察监听器
        into_startDate.addTextChangedListener(textWatcher);
        into_endDate.addTextChangedListener(textWatcher);

//        agent_all = getViewById(R.id.tv_agent_all);
        //add by zhuangzeqin 2017年9月27日09:01:43  改造代理商名称支持模糊查询
        et_agent_input = getViewById(R.id.et_agent_input);
        tv_select_agent = getViewById(R.id.tv_select_agent);

        device_all = getViewById(R.id.tv_device_all);
        card_all = getViewById(R.id.tv_card_all);
        trade_state_all = getViewById(R.id.tv_state_normal);
        trade_state_all.setRightText("已成功");
        cardNum = getViewById(R.id.card_num);
        btn_confirm = getViewById(R.id.btn_confirm);
        phoneLet = getViewById(R.id.let_trade_phone);
        tradeName = getViewById(R.id.let_trade_name_or_number);
    }

    /**
     * add by zhuangzeqin 2017年4月26日09:32:36  根据需求要求修改如下内容
     * 选择了创建时间就不能选择3天内、7天内、一个月内，就不能选择创建时间。
     * 同样选择了创建时间就不能选择3天内、七天内、一个月内。
     */
    private void setSelectTiemEnable(String selectTiem) {
        if (!TextUtils.isEmpty(selectTiem)) {
            for (int i = 0; i < time_select.length; i++) {
                time_select[i].setEnabled(false);//不可用
            }
        } else {
            for (int i = 0; i < time_select.length; i++) {
                time_select[i].setEnabled(true);//可用
            }
        }
    }

    /**
     *  add by zhuangzeqin 2017年4月26日09:32:36  根据标志位；是否要启用进件时间控件
     *
     * @param isenable
     */
    private void setetTimeEnable(boolean isenable) {
        if (isenable) {//不可用
            into_startDate.setEnabled(false);
            into_endDate.setEnabled(false);
        } else {//可用
            into_startDate.setEnabled(true);
            into_endDate.setEnabled(true);
        }
    }

    /**
     * add by zhuangzeqin 2017年4月26日09:32:36
     * 监听文本框内容改变
     */
    private final TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String tempDate = s.toString().trim();//选中的日期时间
            //add by zhuangzeqin 2017年4月26日09:32:36 使用可以启用下边的时间选中标签；比如3天，7天，一个月等
            setSelectTiemEnable(tempDate);
        }
    };

    @Override
    protected void eventOnClick() {
        titleBar.setRightOnClickListener(new TitleBar.RightBtnOnClickListener() {
            @Override
            public void onRightClick(View view) {
                reset();//重置
            }
        });
        for (TextView tv : time_select) {
            tv.setOnClickListener(this);
        }
        trade_state_all.setOnClickListener(this);
//        agent_all.setOnClickListener(this);
        tv_select_agent.setOnClickListener(this);
        device_all.setOnClickListener(this);
        card_all.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);

        TimeUtils.newDateTimePicker(mContext, start_time, TimeUtils.DATE_TIME);
        TimeUtils.newDateTimePicker(mContext, end_time, TimeUtils.DATE_TIME);
        TimeUtils.newDateTimePicker(mContext, into_startDate, TimeUtils.DATE);
        TimeUtils.newDateTimePicker(mContext, into_endDate, TimeUtils.DATE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_select_1:
                changeSelected(time_select, 0);
                break;
            case R.id.tv_select_2:
                changeSelected(time_select, 1);
                break;
            case R.id.tv_select_3:
                changeSelected(time_select, 2);
                break;
            case R.id.tv_state_normal:
                goActivityForResult(TradeStateActivity.class, Constant.RequestCode.trade_state_all);
                break;
//            case R.id.tv_agent_all:
//                goActivityForResult(AgentQueryActivity.class, agent_all);
//                break;
            case R.id.tv_select_agent:
                goActivityForResult(AgentQueryActivity.class, agent_all);
                break;
            case R.id.tv_device_all:
                goActivityForResult(DeviceTypeActivity.class, Constant.RequestCode.device_all);
                break;
            case R.id.tv_card_all:
                Bundle bundle = new Bundle();
                bundle.putString(Constant.INTENT_FLAG, Constant.CARD_TYPE);
                goActivityForResult(ChooseActivity.class, bundle, Constant.RequestCode.card_all);
                break;
            case R.id.btn_confirm:
                queryResult();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case agent_all:
                String agentName = data.getStringExtra("agentName");
//                agent_all.setRightText(agentName);
                et_agent_input.setText(agentName);
                agentNode = data.getStringExtra("agentNode");
                break;
            case Constant.RequestCode.device_all:
                boolean isAll = data.getBooleanExtra("isAll", false);
                if (isAll) {
                    this.device_all.setRightText("全部");
                    hpId = "";
                } else {
                    String device = data.getStringExtra("device_type");
                    if (TextUtils.isEmpty(device)) {
                        this.device_all.setRightText("全部");
                        hpId = "";
                    } else {
                        hpId = data.getStringExtra("hp_id");
                        this.device_all.setRightText(device);
                    }
                }
                break;
            case Constant.RequestCode.card_all:
                String cardType = data.getStringExtra(Constant.CARD_TYPE);
                this.card_all.setRightText(cardType);
                break;
            case Constant.RequestCode.trade_state_all:
                tradeStatusId = data.getStringExtra("trade_status_id");
                this.trade_state_all.setRightText(data.getStringExtra("trade_state"));
                break;
        }
    }

    /**
     * 统计查询条件，跳转结果页面
     */
    private void queryResult() {
        tradeQueryCri = new TradeQueryCri();
//        if (!"全部".equals(agent_all.getRightText())) {
//            tradeQueryCri.setAgentName(agent_all.getRightText());
//            tradeQueryCri.setAgentNode(agentNode);
//        } else {
//            tradeQueryCri.setAgentNode(UserInfo.getUserInfo2SP().getAgentNode());
//        }
        final String agentName = et_agent_input.getText().toString().trim();
        if (!TextUtils.isEmpty(agentName))
        {
            tradeQueryCri.setAgentName(agentName);
            tradeQueryCri.setAgentNode(agentNode);
        }
        else {
            tradeQueryCri.setAgentNode(UserInfo.getUserInfo2SP().getAgentNode());
        }
        if (!"全部".equals(card_all.getRightText())) {
            tradeQueryCri.setCardType(card_all.getRightText());
        }
        for (int i = 0; i < time_select.length; i++) {
            if (time_select[i].isSelected()) {
                tradeQueryCri.setTime(time_select[i].getTag().toString());
            }
        }
        tradeQueryCri.setDeviceName(hpId == null ? "" : hpId);
        tradeQueryCri.setTradeStatus(tradeStatusId);
        tradeQueryCri.setTradeStartTime(getTextContent(R.id.start_time));
        tradeQueryCri.setTradeEndTime(getTextContent(R.id.end_time));
        tradeQueryCri.setTradeMinMoney(trade_minMoney.getText().toString().trim());
        tradeQueryCri.setTradeMaxMoney(trade_maxMoney.getText().toString().trim());
        tradeQueryCri.setCardNum(cardNum.getEditContent());
        tradeQueryCri.setPhone(phoneLet.getEditContent());
        tradeQueryCri.setMerchantName(tradeName.getEditContent());
        tradeQueryCri.setIntoStartTime(into_startDate.getText().toString().trim());
        tradeQueryCri.setIntoEndTime(into_endDate.getText().toString().trim());

        Bundle bundle = new Bundle();
        bundle.putString(Constant.INTENT_FLAG, Constant.TRADE_QUERY);
        bundle.putSerializable(Constant.TRADE_QUERY_CRI, tradeQueryCri);
        goActivity(QueryResultActivity.class, bundle);
    }

    /**
     * 改变选择框的选中状态
     *
     * @param num
     */
    private void changeSelected(TextView[] select, int num) {
        boolean tempSelect = false;//add by zhuangzeqin 2017年4月26日10:15:27 是否选中状态
        for (int i = 0; i < select.length; i++) {
            if (i == num) {
                if (select[i].isSelected()) {
                    select[i].setSelected(false);

                } else {
                    select[i].setSelected(true);
                    tempSelect = true;
                }
            } else {
                select[i].setSelected(false);
            }
        }
        //add by zhuangzeqin 2017年4月26日10:15:27 根据标志位；是否要启用进件时间控件
        setetTimeEnable(tempSelect);
    }

    /**
     * 重置
     */
    private void reset() {
        //重置所有输入框
        setEmpty(start_time, end_time, trade_minMoney, trade_maxMoney
                , into_startDate, into_endDate, phoneLet.getEditText(),
                cardNum.getEditText(), tradeName.getEditText());
//        agent_all.setRightText("全部");
        et_agent_input.setText("");
        et_agent_input.clearFocus();
        card_all.setRightText("全部");
//        trade_state_all.setRightText("全部");
//        tradeStatusId = "";
        trade_state_all.setRightText("已成功");
        tradeStatusId = "SUCCESS";
        device_all.setRightText("全部");
        hpId = "";
        changeSelected(time_select, -1);
    }

    /**
     * 获取TextView的内容， 若TextView为空 则返回“”
     *
     * @param tv
     * @return
     */
    private String getText(TextView tv) {
        if (tv != null) {
            return tv.getText().toString().trim();
        }
        return "";
    }

    /**
     * 输入框置空
     *
     * @param tvs
     */
    private void setEmpty(TextView... tvs) {
        for (TextView tv : tvs) {
            tv.setText("");
        }
    }
}
